Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I have attendance in following table called `Attendance`

`EID` is employee ID and in shift column, `D` denotes a Day shift and `N` denotes a Night shift.
Now I'm trying to get following data pertaining to each employee.
No of Day shifts - count of... | I think you can get what you want using conditional aggregation:
```
SELECT EID,
sum(case when shift = 'd' then 1 else 0 end) as dayshifts,
sum(case when shift = 'n' then 1 else 0 end) as nightshifts,
count(*) as total
FROM Attendance a
WHERE (in_time BETWEEN CONVERT(DATETIME, '2014-01-07 00:00:00... | @Chathuranga, Since Day and Night Shifts of a day should be counted as one, Please let me know if the below solution works for you.
```
DECLARE @Attendance TABLE (EID INT,
PID CHAR(4),
In_Time DATETIME,
Out_Time DATETIME,
Shift CHA... | Shift manipulation in SQL to get counts | [
"",
"sql",
"sql-server",
"ado.net",
"case",
"common-table-expression",
""
] |
1. `select field from table where field = 'value'`
2. `select field from table where field in ('value')`
The reason I'm asking is that the second version allow me to use the same syntax for null values, while in the first version I need to change the condition to 'where field is null'... | When you are comparing a field to a null like `field_name=NULL` you are comparing to a known data type from a field say `varchar` to not only an unknown value but also an unknown data type as well, that is, for `NULL` values. When comparison like `field_name=NULL` again implies therefore a checking of data type for bot... | There is no difference in your example. The second, slightly longer, query is not usually used for a single value, it is usally seen for multiple values, such as
```
select field from table where field in ('value1', 'value2')
``` | is there any difference between the queries | [
"",
"sql",
"select",
"database-performance",
""
] |
I am inserting customer records into a table where, if a record with the same name already exists, I assign the same ID to the newly inserted record.
Assume table T has this record:
```
ID | Name | Phone_Number | Date_Inserted
105| Sam | 111111 | 04/03/2014
106| Rita | 222222 |04/03/2014
```
And I'm ins... | The characterisation of anything as "bad" is subjective. As long as the results are correct, something is only "bad" if it takes too long or uses too many system resources. *You* define "long" and "too many". If something is returning the correct results, in an acceptable time, using an acceptable amount of system reso... | If your schema is not set in stone, I would perhaps reconfigure it so that there is a "person" table and a separate "person phone number" table. With that sort of set up, you can associate multiple phone numbers with one person, and you won't be stomping on IDs, or creating confusing secondary ID columns that aren't pr... | Query to assign the same ID to row being inserted if it it already exists in the table | [
"",
"sql",
"oracle",
"plsql",
""
] |
How can I subtract values in two variables. Here is what I have done so far
```
DECLARE @A NVARCHAR(MAX)
DECLARE @B NVARCHAR(MAX)
SET @A='select count(abc)
from x'
EXEC (@A)
PRINT @A
SET @B= ' select count(xyz)
from y'
EXEC (@B)
PRINT @B
DECLARE @C INT
SET @C = CAST(@A AS INT) - CAST(@B AS INT)
EXEC (@C... | Of course you get a conversion error, because the variable is a string. Even if the string is a query, if you execute it you are not storing the result back to your variable. What you need to do is something along the lines of:
```
DECLARE @A INT, @B INT, @C INT;
SELECT @A = COUNT(abc)
FROM x;
SELECT @B = COUNT(xyz)... | In your code, `@A` and `@B` will hold the sql statements and not the results of them. If you want to run a dunamic sql statement and get some output from it you need to check for [sp\_executesql](http://msdn.microsoft.com/en-us/library/ms188001.aspx) where you may define output parameters.
A proper implementation of y... | subtract variables in SQL | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
I have a table that has a column defined as varray of a defined type. The production table is way more complicated then the following example.
I am able to select the single columns within the type of the varray. But I would like to update the table with a simple update statement (rather than going through a pl/sql ro... | I don't believe you can update a single object's value within a `varray` from plain SQL, as there is no way to reference the `varray` index. (The link Alessandro Rossi posted seems to support this, though not necessarily for that reason). I'd be interested to be proven wrong though, of course.
I know you aren't keen o... | As the Oracle documentation states [here](http://docs.oracle.com/database/121/ADOBJ/adobjcol.htm#ADOBJ7278)
> While nested tables can also be changed in a piecewise fashions,
> varrays cannot.
There is no way to modify VARRAYS in piecewise fashion. The only things you could do are:
* Convert the data type of your fi... | How to update a varray type within a table with a simple update statement? | [
"",
"sql",
"oracle",
"plsql",
""
] |
I have a very weird scenario which i am sure the is an explanation for.
I trying to calculate something and here is the values:
```
SELECT 145.28/63 *(8 * 100) / 100 -- returns: 18.4482480000
```
The problem is that this is not correct, If i do the calculation with Windows Calculator then it returns a more precise ... | the default datatype that is automatically assigned simply doesnt hold the precision you want. This can easily be fixed by explicitly casting your first number as a more precise datatype like this:
```
SELECT CAST(145.28 AS decimal(38,35))/63 *(8 * 100) / 100
--returns 18.448253968253968253968253
```
From there on o... | The result's precision is calculated [based on some factors](http://msdn.microsoft.com/en-us/library/ms190476.aspx) that may give you a scale lower than what you expect. Just try this one:
```
SELECT CONVERT(DECIMAL(38, 35), 145.28)/63 *(8 * 100)
```
which will give you
```
1844.825396825396825396825397
``` | SQL Server calculation gives unexpected results | [
"",
"sql",
"sql-server",
""
] |
I am trying to convert the following query:
```
select *
from employees
where emp_id not in (select distinct emp_id from managers);
```
into a form where I represent the subquery as a join. I tried doing:
```
select *
from employees a, (select distinct emp_id from managers) b
where a.emp_id!=b.emp_id;
```
I also tr... | Try this:
```
select e.*
from employees e
left join managers m on e.emp_id = m.emp_id
where m.emp_id is null
```
This will join the two tables. Then we discard all rows where we found a matching manager and are left with employees who aren't managers. | Assume employee Data set of
```
Emp_ID
1
2
3
4
5
6
7
```
Assume Manger data set of
```
Emp_ID
1
2
3
4
5
8
9
select *
from employees
where emp_id not in (select distinct emp_id from managers);
```
The above isn't joining tables so no Cartesian product is generated... you just have 7 records you're looking at...
Th... | Representing 'not in' subquery as join | [
"",
"sql",
"oracle",
"join",
""
] |
I am using database schema with the following column
```
TRAFFIC_DIRECTION
tinyint
The direction of traffic. Enum ( unknown = 0; inbound = 1; outbound = 2)
```
When I run query, TRAFFIC\_DIRECTION displays as
```
TRAFFIC_DIRECTION
1
2
2
1
1
1
2
2
2
1
1
1
1
1
```
How do I make it such that, instead of outputting 1... | Some RDBMSs support an ENUM type, but all of them support a `CASE` statement.
```
SELECT id,
CASE TRAFFIC_DIRECTION
WHEN 0 THEN 'Unknown'
WHEN 1 THEN 'Inbound'
WHEN 2 THEN 'Outbound'
ELSE 'ERROR'
END
FROM Table1
``` | ```
select case
when traffic_direction = 1 then 'inbound'
when traffic_direction = 2 then 'outbound'
else 'unknown'
end as direction
from the_table;
``` | Format SQL output where value is either 0, 1, or 2 | [
"",
"sql",
""
] |
I have a table with posts in them. Website visitors can upvote or downvote such a post. I want to order a certain sql query by the score of the post, but my `posts` table doesn't have a `score` column - I keep the upvotes and downvotes in a different `votes` table, because that tells me who voted on what. I could add a... | No, you do not have to create a score column. You can order by the calculated score, as below:
Since you do have the upvotes and downvotes in a different table, you need to join, as Tim Schmelter has explained.
```
SELECT p.*
FROM Post p
INNER JOIN Votes v
ON p.PostID = v.PostID
ORDER BY (v.upvotes - v.downvotes);
``... | You have to link both tables via `JOIN`. Presuming that the `Score`-table has a column `PostID`:
```
SELECT p.*, Score = s.Upvotes- s.DownVotes
FROM Post p
INNER JOIN Score s
ON p.PostID = s.PostID
ORDER BY Score
``` | SQL ORDER BY something else than one of the table's columns | [
"",
"sql",
""
] |
my event table with starteventdate and endevent date.
```
Id EventName starteventdate endevent
---------------------------------------
1 a 7/6/2014 8/6/2014
2 b 9/6/2014 10/6/2014
3 c 10/6/2014 15/6/2014
```
my search screen h... | I would do something like this assuming you have `DATETIME` types to work with, instead of strings. You should be able to put the `CONVERT`s back in though, if necessary.
```
SELECT e.EventsID, e.EventDesc AS 'Event Description'
FROM dEvents e
WHERE EndEvent >= @FromDate
AND StartEvent <= @ToDate
``` | Please try this. Observation, you are storing dd/mm/yyyy so use 103 for conversion
**Sample Data:**
```
IF OBJECT_ID(N'dEvents')>0
BEGIN
DROP TABLE dEvents
END
CREATE TABLE dEvents (Id INT,EventName VARCHAR(10),StartEvent VARCHAR(20),endevent VARCHAR(20))
INSERT INTO dEvents VALUES
('1','a','7/6/2014','8/6/2014... | How to write search query in sql server | [
"",
"sql",
"sql-server",
""
] |
I have a table similar to the following in my database
```
+----+----+----+---------------------+
| id | a | b | date_created |
+----+----+----+---------------------+
| 1 | 22 | 33 | 2014-07-31 14:38:17 |
| 2 | 11 | 9 | 2014-07-30 14:40:19 |
| 3 | 8 | 4 | 2014-07-29 14:40:34 |
+----+----+----+----------... | ```
SELECT x.*
, x.a - SUM(y.b)
FROM my_table x
JOIN my_table y
ON y.date_created <= x.date_created
GROUP
BY x.id;
``` | ```
select id, a, a - (select sum(b)
from My_TABLE T2
where T2.date_created <= T1.date_created)
from MY_TABLE T1;
``` | query that subtracts sum of one column from another | [
"",
"mysql",
"sql",
""
] |
I have scoured stack overflow for this with no success.
I'm working on converting some access views, stored procedures, etc to SQL Server 2008.
[I am not very well versed in Access]
This is one statement that has me stumped:
```
IIf([Column1]=0,[Column2],[Column1])
```
Using the `SELECT CASE` statement, I can get t... | There is no reason you can't put a CASE statement into the GROUP BY clause -
```
select case when TABLE1.[COLUMN1] = 0
then TABLE1.[COLUMN2]
else TABLE1.[COLUMN1] end as SomeColumn,
another_col,
canother_col2,
sum(a_dif_col) as sum_a_col
from TABLE1
group by case when TABLE... | You can use subquery:
```
SELECT data.Somecolumn
FROM (
select case
when TABLE1.[COLUMN1]=0 then TABLE1.[COLUMN2]
else TABLE1.[COLUMN1]
end as SomeColumn
) data
GROUP BY data.SomeColumn
``` | What is the SQL Server equivalent of the following Access statement | [
"",
"sql",
"sql-server",
"ms-access",
""
] |
I have a dynamic SQL query which returns rows like below with string values & numeric values.
```
EMP col1 col2 col3 col4 col5
----------------------------
A1 4 4 3 3 3
A2 4 2 5 3 3
A3 sd 3 3 1 sd
A4 3 4 3 3 3
```
Now I need a new column which sums col1 to col5 and c... | You can use a [CASE](http://msdn.microsoft.com/en-us/library/ms181765(v=sql.105).aspx) Expression to determine whether the value is a number. If it is a number then either cast the value to an INT or DECIMAL data type, otherwise use 0 so it doesn't effect the sum.
```
SELECT
CASE WHEN ISNUMERIC(col1) = 1 THEN CAS... | If you're on SQL Server 2012, [TRY\_CONVERT](http://msdn.microsoft.com/en-us/library/hh230993.aspx) avoids [pitfalls commonly encountered with ISNUMERIC](http://classicasp.aspfaq.com/general/what-is-wrong-with-isnumeric.html):
```
SELECT col1, col2, col3, col4, col5,
ISNULL(TRY_CONVERT(int, col1), 0) +
I... | SQL Server Sum rows with string value | [
"",
"sql",
"sql-server",
"t-sql",
"pivot",
""
] |
I'm drawing a blank on the best way write this sql,
For simplicity sake I'm Only interested in one column.
Table A Column = [Supplier].
Table B Column = [AuthorizedSuppliers]
Table A contains many rows with the same value in the [Supplier].
```
Table A
------------------------------
ID |Supplier | Company |
---... | Use `Distinct` and `Left Outer Join`:
```
SELECT DISTINCT Supplier, Authorized = CASE WHEN B.AuthorizedSupplier IS NULL
THEN 'True' ELSE 'False' END
FROM TableA A
LEFT OUTER JOIN TableB B
ON A.Supplier = B.AuthorizedSupplier
```
[**SQL-Fiddle Demo**](http://sqlfiddle.com/#!3/8... | ```
SELECT A.Supplier
, CASE WHEN B.AuthorizedSupplier IS NULL
THEN 'True' ELSE 'False' END AS Authorized
FROM (Select Distinct Supplier
FROM TableA) A
LEFT OUTER JOIN TableB
``` | Distinct SQL that will return true if in a table | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
The method I am using may not be efficient (or possible), if so please let me know.
I am trying to use `SELECT INTO` to select two values and then attach them to a variable (v1) which will be returned by the function as one cell. Inserting `UNION ALL` between the two `SELECT INTO` statements results in an `ERROR: synta... | ```
SELECT cast(t1.value as varchar(20)) || ', ' || cast(t2.value as varchar(20))
INTO v1
FROM table as t1, table as t2
WHERE t1.year <= parameteryear
AND t2.yearinteger >= parameteryear;
``` | If you want to use a union all query, it must be in a derived table.
```
select value
into v1
from (union query goes here) derivedTable
``` | Combining multiple SELECT INTO results into one variable | [
"",
"sql",
"postgresql",
"plpgsql",
"postgresql-9.3",
""
] |
I am working on a SQL query which performs some calculations and returns difference of two columns that belongs to two different rows of single table when certain values in the other columns are not equal
For Example I have the following data in a table
```
id Market Grade Term Bid Offer CP
1 ... | Can you not just change:
```
and r1.CP!=r2.CP
```
to:
```
and ISNULL(r1.CP, 'X') != ISNULL(r2.CP, 'Y')
```
Edit. If you want to be really safe and live a little dangerously you could even do this:
```
and ISNULL(r1.CP, CONVERT(VARCHAR(36), NEWID())) != ISNULL(r2.CP, CONVERT(VARCHAR(36), NEWID()))
``` | I'm not quite throwing this out as an answer because it is an awful solution, but you could replace NULLS with a stand-in value with the [ISNULL](http://msdn.microsoft.com/en-us/library/ms184325.aspx) function.
```
;with numbered as
(
select id, market, grade, term, bid, offer, row_number()
OVER (Partition BY Marke... | Treating null values of two records as not equal in SQL query | [
"",
"sql",
"sql-server-2012",
""
] |
I know this has been a topic that has been discussed in [AWS forums before](https://forums.aws.amazon.com/message.jspa?messageID=396906)
and SO [How to setup sessionState with SQL Server mode on Amazon RDS](https://stackoverflow.com/questions/12636919/how-to-setup-sessionstate-with-sql-server-mode-on-amazon-rds)
As m... | After some digging around I realised that the stored procedures being generated by the [pastebin script](http://pastebin.com/QJDXC093) are still making reference to the tempdb. By doing a simple find replace of [tempdb] to [ASPState] and then re-running the script recreated SP with the correct DB name.
I also changed ... | I've solved my issue create session db on Amazon RDS.
1 Step:- Create ASPState DB on AWS RDS and database and schema migration using Following Tool SQLAzureMW v5.15.6 Release Binary for SQL Server 2014.
2 Step:- change DB Name on sessionState mode="SQLServer" allowCustomSqlDatabase="true" sqlConnectionString="data so... | Using ASP Session State DB on AWS RDS | [
"",
"sql",
"amazon-web-services",
"session-state",
"rds",
"aspstate",
""
] |
I tried connecting to the database server using the command:
```
psql -h host_ip -d db_name -U user_name --password
```
It displays the following line and refuses to connect.
```
psql: FATAL: too many connections for role "user_name".
```
How to close the active connections?
I do not have admin rights for the da... | ### From inside any DB of the cluster:
Catch 22: you need to be connected to a database first. Maybe you can connect as another user? (By default, some connections are reserved for superusers with the [`superuser_reserved_connections`](https://www.postgresql.org/docs/current/runtime-config-connection.html#GUC-SUPERUSE... | I'm pretty new to pgAdmin, but so far I have not utilized the command line. I had the same issue and I found the easiest way to resolve the issue in my case was to simply delete the processes listed in "Database Activity" in the Dashboard.

(just click the X on... | psql: FATAL: too many connections for role | [
"",
"sql",
"postgresql",
"connection",
"psql",
""
] |
I need to select data from the table that looks somewhere about this:
```
monthStart monthEnd newPhones totalPhones oblid
1 1 1 2 1
2 2 1 2 2
1 2 2 2 3
2 2 1 1 4
2 3 ... | So if there is enough data that all months are represented, I think StevieG's answer works. With the smaller data sets like the sample data given, where month 3 is in the monthEnd but not in the monthStart, then there is a problem. Then you need something to make sure all months are represented, which I did with c, the... | Maybe something like this....
```
CREATE TABLE #monthstartdata
(
themonth INT,
themonthcount int
)
CREATE TABLE #monthenddata
(
themonth INT,
totalphones INT,
newphones INT,
)
INSERT INTO #monthstartdata
( themonth, themonthcount )
SELECT monthStart, COUNT(#monthstart) FROM TestGB
GRO... | MySQL get COUNT and SUM on different GROUP BY in one SELECT | [
"",
"mysql",
"sql",
"group-by",
""
] |
I am building a Monthly License Report for our IT department and it receives a list of License information in Euro's. I have an XML feed that provides Exchange rate data daily but the job will only be set to run once a month.
I have a conditional split set up in my SSIS package that splits off the USD exchange rate an... | I actually found a solution for this online that was a little simpler. I have built it, tested it and implemented.
I had to put my foot down with our Network guy and request an outside connection to the internet in order to make it happen (something he wasn't happy about doing) but once we worked that out it worked li... | For the XML posted, this Xpath query will bring you the first element (group of currencies for the first date):
```
'//Cube/Cube[1]/.'
```
if you need to bring only the USD part then:
```
'//Cube/Cube[1]/Cube[@currency="USD"]/.'
```
In SSIS you can apply Xpath transformations through XML task in control flow. | Exchange Rate Return | [
"",
"sql",
"sql-server",
"ssis",
""
] |
I am having a real issue with trying to query my database by selecting the data between 2 dates.
Below is the query I am using within my VB .NET project.
`WHERE [BuildID] > 0 AND [EndDate] BETWEEN '01/07/2014' and '31/07/2014'`
The date format is set to dd/mm/yyyy and the column type is VARCHAR(10)
When I run this ... | > The column type is `VARCHAR(10)`
To have dates treated as dates, you'd need the column type to be `date` (or `datetime` if using older versions of SQL).
If you don't have control over the column type, you'd need to cast to date, but that's going to perform badly with any sizable data set:
```
WHERE [BuildID] > 0
... | Always **always** use [parameterized SQL queries](https://stackoverflow.com/questions/542510/how-do-i-create-a-parameterized-sql-query-why-should-i).
```
Dim date1 As Date = Date.Parse("2014-07-01")
Dim date2 As Date = Date.Parse("2014-07-31")
mycmd.CommandText = ".... WHERE [BuildID] > @bid AND [EndDate] BETWEEN @fi... | SQL SELECT Between 2 Dates | [
"",
"sql",
"sql-server",
"vb.net",
""
] |
I have two tables as follows:
table: **recipe**
fields: **recipe\_ID**, **title**
---
table: **recipe\_ingredient**
fields: **recipe\_ID**, **ingredient\_ID**
---
I would like to show only recipes which contain certain ingredients (I managed to do that part), however I also want to **exclude** recipes which cont... | You could use a sub query that gets any `recipe_ID` which contains the ingredients you **don't** want and then exclude those `recipe_ID`s in the main query:
```
SELECT r.recipe_ID, r.title
FROM recipe r
JOIN recipe_ingredient ri ON ri.recipe_ID = r.recipe_ID
WHERE ri.ingredient_ID IN (4, 7)
AND r.recipe_ID NOT IN
... | You can just rewrite this part of your query.
```
WHERE ri.ingredient_ID not in (4,7)
```
I believe this is what you are looking for since you say your query returns recipes with only certain ingredients. | SQL Query With & Without | [
"",
"mysql",
"sql",
""
] |
I have a PostgreSQL 9.3 database with a users table that stores usernames in their case-preserved format. All queries will be case insensitive, so I should have an index that supports that. Additionally, usernames must be unique, regardless of case.
This is what I have come up with:
```
forum=> \d users
... | First off, practically ***every*** table should have a primary key.
### [`citext`](http://www.postgresql.org/docs/current/interactive/citext.html)
The additional module provides a data type of the same name. "ci" for case insensitive. Per documentation:
> The `citext` module provides a case-insensitive character str... | I would suggest using a primary key, as you have stated you want something that is unique, and as you have demonstrated that you can put unique constraints on a username. I will assume that since this is a unique,not null username that you will use this to track your users in other parts of the Database, as well as all... | What does PRIMARY KEY actually signify, and does my table need one? | [
"",
"sql",
"database",
"postgresql",
"database-schema",
"postgresql-9.3",
""
] |
I need a way to use a particular set of where clauses depending on the comparison of 2 cells in a table. So that if the active date is less then the submit date the count will be based off the submit date where clause otherwise the opposite is done. I have looked at trying to use a CASE but couldn't figure out how to u... | ```
SELECT
SUM(case when Active_Date < Submit_Date and Submit_Date < '2014-07-28' then 1
when Active_Date >= Submit_Date and Active_Date < '2014-07-28' then 1
end) AS OutSLA
FROM
WOI_WorkOrder
WHERE
ASGRP IN ('WOIQUE')
AND
Status = 'Assigned' OR Status = 'Pending' OR Status = 'In P... | Although the other answers are correct, the `WHERE` clauses doesn't have to be this difficult. Because if you think about your `IF` statement, `Active_Date` and `Submit_Date` will both always be less than `2014-07-28`.
So the `WHERE` clause will become
`Active_Date < '2014-07-28' AND Submit_Date < '2014-04-28'` is ... | Use a particular set of where clauses depending on the comparision of 2 cells | [
"",
"sql",
"sql-server",
""
] |
I have the following problem: I want to execute a query on multiple databases on my SQL Server. Every customer has a separate database. Those all have exactly the same table and their names are similar. So there is a database `kde_01_Miller`, then a `kde_02_Mueller` and so on ...
I want to execute a query in every one... | That's not possible, since sp\_executesql is executed as its own self-contained **batch**, that mean you did actually "use" other databases, but only in those batchs i mentioned earlier
I'll try to be more clear, this code of you is a **batch**, since there's no "**GO**" command inside (read my sql comments) :
```
DE... | While this question has already been answered, I thought I'd provide a second answer I believe is better. Instead of using a Cursor you can generate dynamic SQL to query multiple databases.
```
DECLARE @sql NVARCHAR(Max);
SELECT @sql = COALESCE(@sql, '') + 'SELECT * FROM ' + [name] + '.sys.tables' + CHAR(13)
FROM sy... | Script -> Query for multiple databases | [
"",
"sql",
"sql-server",
"database",
"t-sql",
""
] |
I have a mysql table containing 100K mobile numbers (india), but some of them are invalid mobile numbers. I want to delete all mobile numbers that are not exactly 10 digits and starts with digit less than 7.
Can you help me with an sql query for this? | You could do this in 2 simple deletes.
```
DELETE FROM yourtable WHERE Length(MobileNumber) <> 10;
DELETE FROM yourtable WHERE Left(MobileNumber,1) < 7;
```
Or in 1
```
DELETE FROM yourtable WHERE Length(MobileNumber) <> 10 OR
Left(MobileNumber,1) < 7;
``` | Here how you can check the length and start of the digit
```
mysql> select length(5234567896);
+--------------------+
| length(5234567896) |
+--------------------+
| 10 |
+--------------------+
1 row in set (0.00 sec)
mysql> select substr(5234567896,1,1);
+------------------------+
| substr(5234567896... | query to delete invalid mobile numbers from mysql database | [
"",
"mysql",
"sql",
""
] |
Table structure
**employee\_salary**
```
salary_id | emp_id | salary
```
**employee tabe structure**
```
emp_id | first_name | last_name | gender | email | mobile | dept_id | is_active
```
**Department:**
```
dept_id | dept_name | manager_name | is_active
```
**Question:**
Display department wise emplo... | ORDER the salary with DESC for finding the maximum value and by ASC for finding the MINIMUM salary
This is because it checked the first matched term, and return the value accordingly,
```
SELECT max(salary) salary, dept_name, first_name, dept_id , 'MAX' Type
FROM ( SELECT a.salary, c.dept_name, b.first_name, b... | You cannot have in your select list a value that is not an aggregate function or included in your group by. Select the name after you have determined that the employeeid has the highest or lowest salary. | MySQL query to get the max, min with GROUP BY and multiple table joins in separate rows | [
"",
"mysql",
"sql",
""
] |
For testing purposes, I provide my own implementation of the `now()` function which is `public.now()`. Using `search_path` to override the default `pg_catalog.now()` with my own version mostly works, but I have a table with a table with a default expression of `now()`. Showing the table produces something akin to the f... | Default values are parsed at creation time (early binding!). What you see in psql, pgAdmin or other clients is a text representation but, in fact, the `OID` of the function `now()` at the time of creating the column default is stored in the system catalog [`pg_attrdef`](https://www.postgresql.org/docs/current/catalog-p... | The default function is "bound" at the time the default constraint is created. The view showing the unqualified name is simply abbreviating it.
This can be demonstrated by inserting rows before and after shadowing the function:
```
Set search_path to public,pg_catalog;
Create Temp Table foo (
test date not null ... | When / how are default value expression functions bound with regard to search_path? | [
"",
"sql",
"postgresql",
"default",
"search-path",
""
] |
I would like to build a query that returns entries that have been entered in two consecutive weeks.
For example:
```
Name | Country | Date
Name1 | Country1 | 2014-07-29
Name2 | Country2 | 2014-08-08
Name1 | Country2 | 2014-08-07
```
I want to be able to select the entries that are entered on two consecutive... | If your definition of week is "7 days later", then you can do something like:
```
select t.name, t.date
from table t
where exists (select 1
from table t2
where t2.name = t.name and
t.date between t2.date + 7 and t2.date + 14
);
```
Note that different data... | You haven't said what DBMS you are using, and "week" is handled differently in them. The Stack Overflow question [Getting week number of date in SQL](https://stackoverflow.com/questions/15432591/getting-week-number-of-date-in-sql) is a good starting point, or the SQL2003 standard at <http://users.atw.hu/sqlnut/sqlnut2-... | SQL query for checking entries in two consecutive weeks | [
"",
"sql",
""
] |
I am getting this error "Incorrect syntax near '<'.". What's the correct way of using case, comparison operator in where clause?
Here is my Sql query:
```
SELECT COUNT(AL.PKAPPLICATIONID) FROM APPLICATIONLOGO AL
LEFT JOIN THIRDPARTYSESSIONKEY TSK ON AL.PKAPPLICATIONID = TSK.APPLICATIONSOURCEID WHERE
CASE WHEN TSK.CR... | This is your `where` clause:
```
WHERE CASE WHEN TSK.CREATEDON IS NULL THEN TSK.CREATEDON < GETDATE() ELSE 1=1
END
```
I assume you mean `IS NOT NULL`; otherwise the logic doesn't make much sense.
In general, the best way to use `case` in a `where` clause is to avoid it. The following is easier to read and pr... | Use an `OR`:
```
SELECT Count(AL.Pkapplicationid)
FROM APPLICATIONLOGO AL
LEFT JOIN THIRDPARTYSESSIONKEY TSK
ON AL.Pkapplicationid = TSK.Applicationsourceid
WHERE TSK.Createdon IS NULL
OR TSK.Createdon < Getdate()
```
I assume that this is the actual logic since yours makes not sense:
... | What's the correct way of using case in where clause | [
"",
"sql",
"sql-server",
""
] |
I've been trying to come up for answer but no success.
**Need to get:** price for the first purchase and price for the last purchase and grouped by SKU.
Query results should be like this:
```
sku first_purchase_price Last_purchase_price
BC123 3.09 6.68
QERT1 9.09 ... | You can make use of [FIRST/LAST](http://docs.oracle.com/cd/E11882_01/server.112/e26088/functions065.htm#SQLRF51413) aggregate functions to
simplify this type of query.
[SQL Fiddle](http://sqlfiddle.com/#!4/d9ea1/1)
**Query**:
```
select
sku,
max(price) keep (dense_rank first order by purchase_date) f... | It seems your query is missing a GROUP BY clause indeed, if your intention is to
obtain the maximum and minimum "purchase\_DATE" values for a certain value of "sku".
You need to group the columns you're referring to obtain the maximum and minimum values.
With the sample data above, you could try this query:
```
SELECT... | sql - oracle - selecting the first and last record for specific group/sku | [
"",
"sql",
"oracle",
""
] |
I have this table
```
**Original Table**
year month duration amount per month
2012 5 3 2000
```
and I want to get this
```
**Result table**
year month duration amount per month
2012 5 1 2000
2012 6 1 2000
2012 7 1... | try this for SQL SERVER, i included my test temp table:
```
declare @temp as table
(
[year] int
, [month] int
, [duration] int
, [amount] int
)
insert into @temp
(
[year]
, [month]
, [duration]
, [amount]
)
VALUES(
2012
,5
,3
,2000
)
SELECT
[year]
,[month] + n.number
,1
,[amount]
, '1' + SUBSTRING(CAST([du... | Please see the script below that may work for your requirement. I have also compensated for calender year and month increment. Please test and let me know.
```
DECLARE @temp AS TABLE([Year] INT,[Month] INT,Duration INT,Amount INT)
INSERT INTO @temp([year], [month], Duration, Amount)
VALUES (2011, 5, 3, 2000),(2012, 1... | altering a table using sql | [
"",
"mysql",
"sql",
"sql-server",
"t-sql",
""
] |
I currently have two tables in a database. Called Email and unsuscribed both tables have a column called Email. now I want to compare these two tables and wherever email matches I want to update column in email table called Email\_status\_id to 2...the query I am using is
```
UPDATE Email E
SET E.Email_status_id = 2
... | The first thing is to create an index on `Unsubscribed(Email)`:
```
create index idx_unsubscribed_email on unsubscribed(email);
```
Or, even better, declare it as the `primary key`, particularly if it is the only column in the table.
Then, MySQL sometimes does a poor job of implementing `in`. There are a variety of ... | You're doing string comparisons over a large amount of data in an `In` clause. Since you don't actually need the data returned, you can do this in an `Exists`:
```
Update Email E
Set E.Email_status_id = 2
Where Exists
(
Select 1
From Unsubscribed U
Where U.Email = E.Email
)
```
Aside from th... | Query execution is taking too long | [
"",
"mysql",
"sql",
"performance",
"mysql-workbench",
"database-administration",
""
] |
SQL noob here. I'm kind of beat.
So I have a list of data of sales employees like this
```
Employee Name| Sales Timestamp | Item Sold
---------------------
Jackie Chan | 07/11/2014 | TV
Jessica Alba | 08/01/2014 | Sofa
Jessica Alba | 07/25/2014 | Stereo System
Will Ferrell | 06/3... | ```
;WITH SalesCTE AS
(
SELECT [Employee Name],
[Sales Timestamp],
[ITEM SOLD],
ROW_NUMBER() OVER (PARTITION BY [Employee Name] ORDER BY [Sales Timestamp] DESC) AS rn
FROM Sales
)
SELECT [Employee Name],
[Sales Timestamp],
[ITEM SOLD]
FROM SalesCTE
WHERE rn = ... | [**SQL Fiddle**](http://sqlfiddle.com/#!6/bed7e/2/0):
```
SELECT s.[Employee Name], s.[Sales Timestamp], s.[ITEM SOLD]
FROM
(
Select [Employee Name] AS emp, MAX([Sales Timestamp]) AS ts
FROM Sales
GROUP BY [Employee Name]
) AS ss
INNER JOIN Sales s ON ss.emp = s.[Employee Name] AND ss.ts = s.[Sales Timestamp]... | sql server: how to return the latest sales data by employee | [
"",
"sql",
"sql-server",
""
] |
```
declare @nr1 decimal(20,19),
@nr2 decimal(20,19)
set @nr1 = EXP(1.0)
set @nr2 = PI();
print @nr1/@nr2
```
As EXP and PI are "infinite" numbers you should always have enough decimals to print
The result for this query is `0.865255979432265082`
For the query :
```
declare @nr12 decimal(34,25),
@nr... | This link will help: <http://msdn.microsoft.com/en-us/library/ms190476.aspx>
according to this the scale of the result of a division e1/e2 will be given by
this formula max(6, s1 + p2 + 1) and it also includes this note:
* The result precision and scale have an absolute maximum of 38. When a result precision is great... | There is a great explanation here [T-SQL Decimal Division Accuracy](https://stackoverflow.com/questions/423925/t-sql-decimal-division-accuracy)
```
--Precision = p1 - s1 + s2 + max(6, s1 + p2 + 1)
--Scale = max(6, s1 + p2 + 1)
--Scale = 15 + 38 + 1 = 54
--Precision = 30 - 15 + 9 + 54 = 72
--Max P = 38, P & S are link... | SQL Server Decimal precision | [
"",
"sql",
"sql-server",
"decimal",
""
] |
I have this Table
```
CREATE TABLE [dbo].[Room] (
[Id] INT IDENTITY (1, 1) NOT NULL,
[Name] NVARCHAR (32) NOT NULL,
[Capacity] TINYINT NOT NULL,
[CapacityOccupied] TINYINT NOT NULL,
CONSTRAINT [PK_Room] PRIMARY KEY CLUSTERED ([Id] ASC)
);
```
And Data in Table is:
... | Try this way:
```
SELECT CASE
WHEN (Capacity-CapacityOccupied)= Capacity
THEN 'Empty'
when (Capacity-CapacityOccupied)=0
then 'Full'
else cast((Capacity-CapacityOccupie) as varchar(10))
END as Salable, *
FROM Room
``` | Try :
```
SELECT
CASE
WHEN (Capacity-CapacityOccupied)= Capacity
THEN 'Empty'
WHEN (Capacity-CapacityOccupied)=0
THEN 'Full'
ELSE
CAST((Capacity-CapacityOccupied) AS nvarchar(100))
END AS Salable, *
FROM Room
``` | use IF…THEN Sql query and return int and String | [
"",
"sql",
"sql-server",
"if-statement",
""
] |
I have the following table of messages (sid = sending correspondent ID, rid = receiving correspondent ID, mdate = message date, mtext = message text) representing a correspondence among parties:
```
sid|rid| mdate | mtext
---+---+------------+----------
1 | 2 | 01-08-2014 | message1 <-- 1st m. in corresp. be... | group by sid if rid=1 or rid if sid=1 to find max date, then join:
```
select a.*
from messages a
join (
select if(sid=1, rid, sid) id, max(mdate) d
from messages
where sid = 1 or rid = 1
group by id) b on ((a.sid=1 and a.rid=b.id) or (a.sid=b.id and a.rid=1)) and a.mdate = b.d;
```
[demo](http://sqlfiddle.co... | Assuming that there are no messages with the exact same timestamp between two correspondents, you can use a filtering join:
```
select *
from messages m
join (
select case when sid > rid then sid else rid end r1
, case when sid <= rid then sid else rid end r2
, max(mdate) as... | Last message in correspondence | [
"",
"mysql",
"sql",
""
] |
I have the following table:
```
| id | msgType | user | job_id | project_id |
|+++++++++++++++++++++++++++++++++++++++++++|
| 1 | 1 | 1 | 1 | 1 |
| 2 | 1 | 1 | 2 | 1 |
| 3 | 2 | 1 | 3 | 1 |
| 4 | 2 | 1 | 4 | 1 |
| 5 | 1 ... | ```
SELECT * FROM
(
SELECT msgType ,user, min(job_id), project_id
FROM mail
WHERE msgType = 1
GROUP BY msgType,user,project_id
UNION ALL
SELECT msgType ,user, job_id, project_id
FROM mail
WHERE msgType <> 1
)T ORDER BY T.msgType Desc
```
Fiddle here: <http://sqlfid... | To do it all in one statement you could do this:
<http://sqlfiddle.com/#!2/5708b8/16>
```
SELECT msgType
, min(user) user
, min(job_id) job_id
, project_id
FROM mail
group by msgType
, project_id
, case when msgType = 1 then user else job_id end
```
Though I suspect the `union all` methods above are simpler to under... | MySQL if statement in GROUP BY | [
"",
"mysql",
"sql",
""
] |
I have my table below:
```
| id | version | type | test_id | value |
+------+---------+----------+---------+--------------------+
| 1235 | 0 | 600 | 111 | 2 |
| 1236 | 0 | 600 | 111 | 2 |
| 1237 | 0 | 600 | 111 | 2 |
| 1238 | 0 | 601 | 111 | 1 |
| 1239 | ... | You can group by type and value.
[SQL Fiddle Example](http://sqlfiddle.com/#!2/98091/2)
```
select type,
value,
count(*)
from answer
-- add your where clause
group by type, value
``` | ```
select value, count(*) from a where type=600 group by value
``` | Mysql logic to count | [
"",
"mysql",
"sql",
"count",
""
] |
I have a field in the database that contains a lot of empty/null rows. I am trying to create a case statement that changes this to "Empty Field" or something similar so that when it is displayed to the user, they will have an indication that the row has no data for that column but for some reason it is not working. Whe... | You should use `nvl()` as codenheim suggested, but further to the answers about your original solution, you have no `else` clause - so nothing is matching against `= null` and you never get `Empty field`, but everything that *doesn't* match is then defaulted to null anyway. You'd need to do:
```
SELECT CASE
WHEN ... | In Oracle, `''` in VARCHAR context is treated as NULL
You can just use NVL(col\_name,'Default Value')
```
select NVL(col_name, 'Empty Field') from table_name
```
TRIM('') is NULL in Oracle SQL, so has no effect.
```
SQL> set null NULL
SQL> select trim('') from dual;
T
-
N
U
L
L
```
As far as your CASE statement, ... | Case statement not working as expected in Oracle | [
"",
"sql",
"oracle",
""
] |
I am looking for a way to only select the value of a column if it is unique.
Example of data in table:
```
Name City Age
-----------------------
James New York 20
Charles New York 21
Tom New York 22
```
Example of output of select all query:
```
Name City Age
-------------------... | Use a join to other cities, and mask duplicates:
```
select distinct
p.name,
case when p2.city is not null then null else p.city end city,
p.age
from person p
left join person p2 on p.name = p2.name
and p.city != p2.city
```
`distinct` makes only one row result for duplicate cities.
This query relies ... | I don't believe that the accepted answer addresses OP's question, because it only checks the uniqueness across the cities of person with the same name. It also doesn't satisfy the second provided dataset.
The following query checks the uniqueness **across the entire column** and satisfies the example output for the in... | Select Column if Unique in SQL | [
"",
"sql",
"sql-server",
""
] |
I have a question about `SHOW COLUMNS FROM table like 'column name'"`.
I have already tried some tests for some times, it seems be similar like "where `column name='column'`.
However, I just would like to confirm
thank u very much in advance.
Also, I'd like to say, why cannot I use `SHOW COLUMNS FROM table = 'columnn... | It's more like
```
WHERE column_name LIKE 'column name'
```
Since it uses `LIKE`, you can put wildcard patterns in the parameter, e.g.
```
SHOW COLUMNS FROM table LIKE '%id'
```
will find all columns that end in `id`.
If there are no wildcard characters, then `LIKE` is equivalent to `=`.
If you don't want to use ... | maybe this:
SHOW COLUMNS FROM accounts LIKE'id' | mysql query "SHOW COLUMNS FROM table like 'columnname'":questions | [
"",
"mysql",
"sql",
""
] |
I have FACULTY table which contain the column with other table's id's separated by commas. I want to join those with respective table.
`faculty` table:
```
id | name | course_id | subject_id
a | smith | 2,3 | 1,2
```
`course` table:
```
id | name
1 | bcom
2 | mcom
3 | bba
```
`subject` table:
```
id | ... | You can do the following query
```
select * from faculty F
JOIN course C
on CHARINDEX((','+CAST(c.id as varchar(10))+','), (','+f.courseid+',')) > 0
JOIN subject s
on CHARINDEX((','+CAST(s.id as varchar(10))+','), (','+f.subjectid+',')) > 0
``` | I do not think the performance will be too nice but worths trying. This solution would work in `SQL SERVER`:
```
SELECT *
FROM faculty F
JOIN course C
ON ','+F.course_id+',' LIKE '%,'+CONVERT(VARCHAR,C.ID) +',%'
JOIN subject S
ON ','+F.subject_id_id+',' LIKE '%,'+CONVERT(VARCHAR,S.ID) +',%'... | Join table using columns which contains other table's id's separated by commas | [
"",
"sql",
"join",
""
] |
I'm working on a database structure and trying to imagine the best way to split up a host of related records into tables. Records all have the same base type they inherit from, but each then expands on it for their particular use.
These 4 properties are present for every type.
```
id, name, groupid, userid
```
Here ... | Make the design as simple as possible.
First I'd try a single table that contains all attributes that might apply to a record. Irrelevant attributes can be `null`. You can enforce `null` values for a specific type with a `check` constraint.
If that doesn't work out, you can create three tables for each record type, w... | This is a typical "object-oriented to relational" mapping problem. You can find books about this. Also a lot of google hits like
<http://www.ibm.com/developerworks/library/ws-mapping-to-rdb/>
The easiest for you to implement is to have one table containing all columns necessary to store all your types. Make sure you ... | Multiple record types and how to split them amongst tables | [
"",
"sql",
""
] |
I need to update table from result another table.
I have some tables
```
Table people
|id|level|
1 0
2 0
3 0
```
and Table games
```
|id | idman | win_or_lose | game |
1 1 win 1
2 2 lose 1
3 1 win 2
4 3 ... | I would do this like this: (**Fiddle:** <http://sqlfiddle.com/#!2/1c29e/1/0>)
```
update people p join (select idman, count(*) as max_game
from games
where win_or_lose = 'win'
group by idman) x on p.id = x.idman
set p.level = x.max_game
``` | You could try this(I believe idman is the FK of peoples Id column)
```
UPDATE
people
JOIN (SELECT idman FROM games WHERE win_or_lose="win" GROUP BY game)a
ON people.id=a.idman
SET level=level+1
;
```
If the same people wins several different games. The level counter will keep on increasing. | Fix query to mysql | [
"",
"mysql",
"sql",
""
] |
I have a situation where I need to convert the datetime value stored as string to Timestamp:
*I am using oracle database*
This actually works for me `select TO_DATE('11-27-2013 21:28:41', 'MM-DD-YYYY HH24:MI:SS') from dual;`
But my date value now is diffent from the above:
`select TO_DATE('Sunday 6/1/2014 8:00AM', '... | You have to specify a correct format mask to the `TO_DATE` function. See a full list of format masks along with documentation for the function here: <http://www.techonthenet.com/oracle/functions/to_date.php>
You can correct your problem by:
```
SELECT TO_DATE('Sunday 6/1/2014 8:00AM', 'DAY M/D/YYYY HH:MIAM') FROM DUA... | Try using the correct format. I think this will work:
```
select TO_DATE('Sunday 6/1/2014 8:00AM', 'DAY MM/DD/YYYY HH:MI AM')
```
[Here](http://www.sqlfiddle.com/#!4/d41d8/33525) is a SQL Fiddle. | Converting String Date to Date Time in Oracle | [
"",
"sql",
"oracle",
"date",
"datetime",
""
] |
I have 2 tables in sybase
**Account\_table**
```
Id account_code
1 A
2 B
3 C
```
**Associate\_table**
```
id account_code
1 A
1 B
1 C
2 A
2 B
3 A
3 C
```
I have this sql query
```
SELECT * FROM account_table account, associate_table assoc
WHERE account.acc... | ```
SELECT b.id account_id,a.code account_code,a.id assoc_id
FROM associate a,
account b
WHERE a.code = b.code
AND a.id IN (SELECT a.id
FROM associate a,
account b
WHERE a.code = b.code
GROUP BY a.id
... | Try this
```
SELECT AC.ID,AC.account_code,ASS.ID
FROM account_table AC INNER JOIN associate_table AS ASS ON AC.account_code = ASS.account_code
``` | SQL joining two tables with common row | [
"",
"sql",
"sybase",
""
] |
I have lost few hours looking for one row solution and didn't manage to find it.
I have some value `(2013/01/03 07:13:26.000)` and I want to extract time part to get this: `07:13:26` so I can store it in another database as stage layer in ETL process.
When I try `select my_datetime::datetime hour to second`, I still g... | Ok, I managed to do this:
```
SELECT to_char(extend (my_datetime_column, hour to second),'%H:%M:%S') as my_time FROM my_table
```
Hope it will help someone! | Try this:
```
SELECT CAST(datetime_field AS DATETIME HOUR TO SECOND) ...
```
Or
```
SELECT to_char(datetime_field, "%H:%M:%S") ...
``` | Extract TIME from DATETIME - informix | [
"",
"sql",
"timestamp",
"informix",
"etl",
""
] |
I'm new to SQL and am not a programmer. Struggling with the following. Finally I give up and ask for your help.
```
SELECT `AccountNo`, -SUM(`Amount`) AS "Charged"
FROM `databasenamex`.`tablenamex`
WHERE (`Charge progress` BETWEEN 1 AND 2)
OR IFNULL(`Charge progress` BETWEEN 1 AND 2, 0)
GROUP BY `AccountNo`;
```
Th... | Not sure I understood your problem, but here's a try:
```
SELECT `AccountNo`, -SUM(`Amount`) AS "Charged"
FROM `databasenamex`.`tablenamex`
WHERE COALESCE(`Charge progress`, 1) BETWEEN 1 AND 2
GROUP BY `AccountNo`;
```
COALESCE is a function that returns it's leftmost not null value. so if `Charge progress` is null, ... | This seems to be what you want:
```
SELECT `AccountNo`, -SUM(`Amount`) AS "Charged"
FROM `databasenamex`.`tablenamex`
WHERE `Charge progress` BETWEEN 1 AND 2 OR
`Charge progress` IS NULL
GROUP BY `AccountNo`;
```
Your question, though, says that you want all of the rows. Why are you using a `where` clause at al... | sql query to include null | [
"",
"mysql",
"sql",
""
] |
I want to determine the AND clause based on the value of the current row. So for example, my job table has 4 date columns: offer\_date, accepted\_date, start\_date, reported\_date. I want to check against an exchange rate based on the date. I know the reported\_date is never null, but it's my last resort, so I have a p... | Should just be a simple coalesce, so something like:
```
SELECT *
FROM job j
INNER JOIN exchange_rate er
ON j.currency_id = er.currency_id
AND er.date = COALESCE( offer_date, accepted_date, start_date, reported_date )
``` | CASE statement in a where clause.
```
CASE WHEN offer_date is not null THEN offer_date
WHEN accepted_date IS NOT NULL THEN accepted_date
WHEN start_date IS NOT NULL THEN start_date
WHEN reported_date IS NOT NULL THEN reported_date
ELSE '' END
```
it will work as per your require condition | SQL Conditional AND | [
"",
"sql",
"join",
"case",
"conditional-statements",
""
] |
I'm looking for an efficient way to find all the intersections between sets of timestamp ranges. It needs to work with PostgreSQL 9.2.
Let's say the ranges represent the times when a person is available to meet. Each person may have one or more ranges of times when they are available. I want to find *all* the time per... | I created the `tsrange_interception_agg` aggregate
```
create function tsrange_interception (
internal_state tsrange, next_data_values tsrange
) returns tsrange as $$
select internal_state * next_data_values;
$$ language sql;
create aggregate tsrange_interception_agg (tsrange) (
sfunc = tsrange_intercepti... | If you have a fixed number of entities you want to cross reference, you can use a cross join for each of them, and build the intersection (using the `*` operator on ranges).
Using a cross join like this is probably less efficient, though. The following example has more to do with explaining the more complex example be... | Find all intersections of all sets of ranges in PostgreSQL | [
"",
"sql",
"postgresql",
"date-range",
""
] |
I am trying to find out total count of clientIds that are distinct in my table
here are the queries
```
$stmt = $conn->prepare("SELECT DISTINCT count(clientId) as totalrecords FROM quotes WHERE storeEmail = '". $store['email']. "'");
$stmt->execute();
$totalRecords = $stmt->fetch(PDO::FETCH_COLUMN... | [`COUNT DISTINCT`](http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_count) is what you're looking for:
```
$query = "SELECT COUNT(DISTINCT clientId) FROM quotes WHERE storeEmail = '". $store['email']. "'";
``` | `SELECT DISTINCT count(clientId)` will return you count of clientId , whether you use DISTINCT OR not.
But the second query will return the distinct clietIds.
And you should to use
`SELECT count(DISTINCT clientId)` | SELECT Distinct table items from a table in mysql | [
"",
"mysql",
"sql",
""
] |
I am sure it was asked before but I just can't figure out how to search for it
I have a table table1:
```
| RefId_1 | RefId_2 |
---------------------
| 1 | 133 |
| 3 | 12 |
| 4 | 144 |
| 4 | 22 |
| 3 | 123 |
```
I need to get list of `RefId_1` which do have referen... | **UPDATED** : (**UNTESTED**)
```
SELECT DISTINCT REF_ID1 FROM table1
WHERE REF_ID2 IN(133,22,44)
AND
REF_ID1 NOT IN
(SELECT REF_ID1 FROM table1 WHERE REF_ID2 IN (12, 144, 111))
``` | Try this It must work which you want
```
SELECT DISTINCT REF_ID1
FROM table1
WHERE REF_ID1 NOT IN
(SELECT REF_ID1
FROM table1
WHERE REF_ID2 IN (12,144));
``` | Get rows which do have references to list of values and at the same time don't have any references to list of other values | [
"",
"mysql",
"sql",
""
] |
I have SQL Server 2008 query that displays `Start_of_Attack` and `End_of_Attack`:
```
SELECT
CAST (DATEADD(SECOND, dbo.AGENT_SECURITY_LOG_1.BEGIN_TIME /1000 + 8*60*60, '19700101') AS VARCHAR(50)) as Start_of_Attack,
CAST (DATEADD(SECOND, dbo.AGENT_SECURITY_LOG_1.END_TIME /1000 + 8*60*60, '19700101') AS VARCHAR... | Since you're storing your date as an integer, you can just do:
```
SELECT (dbo.AGENT_SECURITY_LOG_1.END_TIME
- dbo.AGENT_SECURITY_LOG_1.BEGIN_TIME )/1000 as Duration_Of_Attack
```
If the values were stored as `DATETIME` you could use `DATEDIFF()` easily, as it is you can still use `DATEDIFF()` but it requires c... | Your times look like they are in a Unix format of milliseconds since a reference time. So just take the difference:
```
SELECT (dbo.AGENT_SECURITY_LOG_1.END_TIME - dbo.AGENT_SECURITY_LOG_1.END_TIME) / 1000 as diff_in_seconds
``` | SQL Server 2008 - Display time difference | [
"",
"sql",
"sql-server-2008",
"datetime",
""
] |
I'm working with SAP Business One in a formatted search and have run into some syntax I am unfamiliar with or haven't come across before. This is probably pretty basic but can anybody shed some light on this please?
Ignore the $[system objects].
```
DECLARE @parent nVarChar(15)
SET @parent = (SELECT T0.FNum
FROM OACT... | Select [VALUE] will return just a value.
**Oracle:**
```
select 'Hello' from Dual
```
**SQL Server:**
```
Select 'Hello'
```
So what your code seems to be doing is setting/displaying a value, nothing more.
An example of another way you can use it, multiple items within a select:
<http://sqlfiddle.com/#!2/a2581/2... | `Select XX` will return `XX`.
For Example I've three rows in my table bookings and I do `select 21 from tablename` then I'll get the following result

and if i just do `select 21` , it will give me this
 from reviews )`
here you go !!! | ```
SELECT * from reviews where rating = (SELECT MIN(rating) from reviews )
``` | Struggling with an SQL query | [
"",
"mysql",
"sql",
""
] |
Can any body tel me how to overcome this error when taking a backup in SQL Server 2008 Express?
```
Backup failed for Server '\SQLEXPRESS'. (Microsoft.SqlServer.SmoExtended)
For help, click: http://go.microsoft.com/fwlink?ProdName=Microsoft+SQL+Server&ProdVer=10.50.1447.4+((KJ_RTM).100213-0103+)&EvtSrc=Microsoft.Sql... | The backup statement is using the `NOINIT` clause. This causes each successive backup to append to the existing backup file. You are attempting to backup to one media set (one file), but it appears the existing backup you are attempting to append to consisted of two media sets (two files).
For a quick turnaround, spec... | A simple solution has arisen (via SSMS), based on the [answer of @DMason](https://stackoverflow.com/questions/25086022/backup-failed-for-server-the-media-is-formatted-to-support-2-media-families-err/25086435#25086435) and [answer of @Carol Baker West](https://dba.stackexchange.com/a/33320/127892).
[![enter image descr... | Backup failed for Server, The media is formatted to support 2 media families Error | [
"",
"sql",
"t-sql",
"sql-server-express",
"database-backups",
""
] |
I'm trying to create a view based on an existing table.
The table will be like:
```
+------+------+------+------+
| col1 | col2 | col3 | col4 |
+------+------+------+------+
| 1 | a1 | a2 | a3 |
| 2 | b1 | b2 | b3 |
| 3 | c1 | c2 | c3 |
| 4 | d1 | d2 | d3 |
| 5 | e1 | e2 | e3... | It is very likely that your MySQL instance is configured to [treat double-quoted strings as string literals rather than quoted identifiers](http://dev.mysql.com/doc/refman/5.0/en/sql-mode.html#sqlmode_ansi_quotes "Server SQL Modes – ANSI_QUOTES"). If you use MySQL's native backticks to delimite the names in ORDER BY, [... | Try:
```
select * from (
(select col1 as col1,col2 as col2,col4 as col3 from t1)
union
(select col1 as col1,col3 as col2,col4 as col3 from t1)
) as t
order by t.col2,t.col3
```
In your case only the second query will order the result. | SQL ORDER BY with UNION | [
"",
"mysql",
"sql",
"sql-order-by",
"union",
""
] |
I have this problem I've been working on for a while, and I just haven't been able to figure out what's wrong with my query. Today, I finally got a bit closer, and now I think I'm pretty close and not too far from succeeding, but I need your help to spot the mistake in this query, because I think I've stared blind on i... | I think below is the final query that you need. I have used alias as `TAB1,TAB2 and TAB3` for clarity and to avoid confusion. Change it as required.
```
SELECT * FROM Users TAB1
INNER JOIN webpages_UsersInRoles TAB2
ON TAB2.UserId = TAB1.UserId
INNER JOIN webpages_Roles TAB3
ON TAB2.RoleId = TAB3.RoleId
WHERE TAB1.U... | You have to use an alisas for the tables:
```
SELECT * FROM Users
INNER JOIN webpages_UsersInRoles w1 ON w1.webpages_UsersInRoles.UserId = Users.UserId
INNER JOIN webpages_UsersInRoles w2 ON w1.webpages_UsersInRoles.RoleId = w2.webpages_Roles.RoleId
WHERE Users.UserId = 1
``` | Two inner joins with same tables | [
"",
"sql",
"sql-server",
"inner-join",
""
] |
I have a table that has multiple rows for the same ID. I need to return a count of the distinct IDs which have no rows that contain a value. I have tried something like this:
```
SELECT COUNT(DISTINCT studID) AS 'ID'
FROM all_classes WHERE absences=0
AND (SELECT DISTINCT studID
FROM all_classes
... | I think you were very close. I would have used a NOT IN subquery. And I don't think the first where criteria was necessary.
This should pull any student id where all rows of the id have absences=0
```
SELECT COUNT(DISTINCT studID) AS 'ID'
FROM all_classes WHERE studID NOT IN
(SELECT DISTINCT studID
FROM al... | The correct way to rewrite your query is like this:
```
SELECT COUNT(DISTINCT studID) AS 'ID' -- 'total students' makes more sense?
FROM all_classes
WHERE studID NOT IN(
SELECT studID
FROM all_classes
WHERE absences <> 0
)
```
However, when you're not actually selecting something using a subquery it's b... | Get a count of distinct rows that does not include a value in any row | [
"",
"sql",
"sql-server",
""
] |
I will try to present the situation as a minimal example:
Say we have a table of tickets, defined as follows:
```
CREATE TABLE ticket_id_list (
ticket_id NUMBER,
issued_to VARCHAR2(100),
CONSTRAINT ticket_id_list_pk PRIMARY KEY (ticket_id)
);
```
The system is used for some time and data is added to the t... | You could add a check constraint where values after a certain date cannot be null; something like:
```
alter table ticket_id_list
add constraint nul_ref
check (ticket_id < 123456 or ref is not null);
```
This does presume that ticket\_id's only go up over time, if you happen to have a date field in your table it ... | I found a neat trick: [`NOVALIDATE`](http://richardfoote.wordpress.com/2008/07/28/novalidate-constraints-no-really/).
Add a nullable column:
```
ALTER TABLE ticket_id_list
ADD ref_no VARCHAR2(6);
```
And then add a table contraint, but make sure to specify `NOVALIDATE`:
```
ALTER TABLE ticket_id_list
ADD CONS... | Make NOT NULL constraint apply only to new rows | [
"",
"sql",
"oracle",
"constraints",
""
] |
I got a numeric value in Foo.A and it has its equivalent in Bar but with a string prefix ("Z"). I'm trying to **append the "Z" to the Bar.A col value**. I also tried with `CONCAT` but without any success. This following codes returns "Unknown column Z".
```
UPDATE Foo, Bar
SET Foo.B = Bar.B
WHERE Foo.A = Z + Bar.A
```... | If your syntax works, then it is likely you are using MySQL. In any case, the problem is that you need quotes around string constants. So try this:
```
UPDATE Foo join
Bar
on Foo.A = concat('Z', Bar.A)
SET Foo.B = Bar.B;
```
You should always use single quotes for string and date constants, regardle... | You are missing the single quotes around Z i.e. your code should be:
```
UPDATE Foo, Bar
SET Foo.B = Bar.B
WHERE Foo.A = CONCAT('Z', Bar.A);
``` | SQL CONCAT String + Column in WHERE clause | [
"",
"mysql",
"sql",
"concatenation",
"where-clause",
""
] |
I have the following two tables:
```
CREATE TABLE [dbo].[ApplicationServers]
(
[ServerName] [nchar](10) NOT NULL,
[ApplicationName] [nchar](10) NULL
)
GO
CREATE TABLE [dbo].[Alerts]
(
[ServerName] [nchar](10) NULL,
[AlertDescrption] [nchar](10) NULL,
[AlertStatus] [int] NULL
)
GO
```
Sample data:
``... | ```
SELECT
a.*,
CASE ax.Highest
WHEN 2 THEN 'Error'
WHEN 1 THEN 'Warning'
ELSE 'Normal' END
FROM ApplicationServers a
OUTER APPLY
(
SELECT MAX(AlertStatus) AS Highest
FROM Alerts b
WHERE a.ServerName = b.ServerName
) ax
```
OUTER APPLY involves two tables A and B and is helpful for doing requests on ta... | You can also do this by using LEFT OUTER JOIN.
[SQL Fiddle here](http://sqlfiddle.com/#!3/a7942/11)
```
SELECT aps.ServerName,
aps.ApplicationName,
CASE
WHEN a.AlertStatus = 1 THEN 'Warning'
WHEN a.AlertStatus = 2 THEN 'Error'
ELSE 'Normal'
END A... | Results Dependent on Values in other table | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I have a table of winners vs losers (TABLE1) e.g.
```
+----+--------+-------+
| ID | Winner | Loser |
+----+--------+-------+
| 1 | 2 | 3 |
| 2 | 1 | 2 |
+----+--------+-------+
```
In the most recent game between Item 1 and Item 2, 1 won (ID 2). For this example, I'll refer to this as C... | You can do it this way, by explicitly looking for certain records (a match between the two items) and counting to see if there are zero of them.
CURRENTLOSER and CURRENTWINNER are placeholders for variables or whatever.
```
select previous.loser
from table1 previous
where previous.winner=CURRENTLOSER and (
select ... | The query below will insert inferred losers for the most recent match between 1 and 2 the first time it's run. The second time it won't insert any new rows.
Initially the `not exists` subquery had `where id < current.id` to remove previous losers, however, since inferred games are inserted with 'future' ids (i.e. 3 in... | Excluding results of nested SQL query | [
"",
"mysql",
"sql",
""
] |
I have this query
```
SELECT COUNT(*) from `login_log` where from_unixtime(`date`) >= DATE_SUB(NOW(), INTERVAL 1 WEEK);
```
and the same one with 1 diff. it's not **1 WEEK** , but **1 MONTH**
how can I combine those two and assign them to aliases? | I would do this with conditional aggregation:
```
SELECT SUM(from_unixtime(`date`) >= DATE_SUB(NOW(), INTERVAL 1 WEEK)),
SUM(from_unixtime(`date`) >= DATE_SUB(NOW(), INTERVAL 1 MONTH))
FROM `login_log`;
```
MySQL treats boolean values as integers, with `1` being "true" and `0` being "false". So, using `sum()` ... | Even though it's pretty tough to understand what you ask:
If you want them in the same column use `OR`
```
SELECT COUNT(*) from 'login_log' where from_unixtime('date') >= DATE_SUB(NOW(), INTERVAL 1 WEEK) OR from_unixtime('date') >= DATE_SUB(NOW(), INTERVAL 1 MONTH) ;
```
If you don't want duplicate answers: use `GRO... | Combine 2 MySQL queries | [
"",
"mysql",
"sql",
""
] |
I have 3 tables for example
**Parent Table :TEST\_SUMMARY**
**Child Tables : TEST\_DETAIL, TEST\_DETAIL2**

I have data show in image, and want output result shown in image,
I tried below 2 query, but not giving expected output
```
SELECT s.NAME, sum(s.AMT), s... | One way to solve it for both MySQL and Oracle is to use subqueries to help solve the duplication for you by aggregating the sums from the details tables by name, so you can summarise with a normal join;
```
SELECT ts.name, SUM(ts.amt) amt1, MAX(td1.amt) amt2, MAX(td2.amt) amt3
FROM TEST_SUMMARY ts
LEFT JOIN (
SELECT... | You could try this:
```
SELECT
TEST_SUMMARY.NAME,
TEST_SUMMARY.AMT AS AMT1,
(
SELECT
SUM(TEST_DETAIL.D_AMT)
FROM
TEST_DETAIL
WHERE
TEST_DETAIL.SUMMARY_ID=TEST_SUMMARY.ID
) AS AMT2,
(
SELECT
SUM(TEST_DETAIL2.D2_AMT)
... | Select query with left outer join and sum with group by | [
"",
"mysql",
"sql",
"oracle",
"left-join",
""
] |
Being new to phpMyAdmin, I want to create a relation between a column (`column_1`) of one of my tables (`Table_1`) with a column (`column_2`) in another table (`Table_2`).
I first index `column_1` in `Table_1` and when I want to create the relation in relation view tab of `Table_1`, in front of `column_1`, I first cho... | I don't know what's wrong with PMA. Following query should create the reference. If that fails the error-message will exlpain more ;)
```
ALTER TABLE `this_table`
ADD CONSTRAINT `name_of_the_constraint` FOREIGN KEY (`this_column`)
REFERENCES `external_table` (`external_column`)
ON DELETE CASCADE ON UPDAT... | To clarify:
Table\_1 has an index column1
Table\_2 has a column2 that you want to use as a foreign key into Table\_1
I think you need to make column1 a Primary Key for Table\_1 in order for this to work.
Once you do that, the third drop-down in relationship view for Table\_2 will have column\_1 as a value that you c... | Creating a relationship in phpMyAdmin | [
"",
"mysql",
"sql",
"phpmyadmin",
""
] |
We have a table that contains all of our products. In here is a column called UNITMEASURE. This column is populated with values such as "EA, PR, PK, YD, etc". Occasionally a 1 will get populated into this column. I would like to run an update statement to change the 1's to whatever the other values are.
For example:
... | Try this way:
```
update producttable
set UNITMEASURE = case WHEN PRODUCT = 1234
THEN = 'PR'
WHEN PRODUCT = 4321
THEN = 'EA'
ELSE = UNITMEASURE
END
```
for updated question
```
update producttable
set UNITME... | Try this way:
```
update yourtable
set UNITMEASURE = (case when PRODUCT=1234 then 'PR'
when PRODUCT=4321 then 'EA'
else UNITMEASURE
end)
where UNITMEASURE <> 1
``` | SQL Update Multiple Rows value based on same row | [
"",
"sql",
"sql-server",
"sql-update",
""
] |
let me first i put my code :
```
SELECT REPLACE(SUBSTRING(CreateDate,3,8),'/','') as registerdate,
FROM TatEstelam.dbo.tblInquiryRealForeigners RL
LEFT JOIN TatEstelam.dbo.CustomerInfo CINFO
ON RL.IdentificationDocumentNumber = CINFO.NationalID
WHERE-- NationalID <> '0001'
Ident... | As you said you can't use alias in where clause - it's true.
You should use whole expression instead as below.
```
SELECT REPLACE(SUBSTRING(CreateDate,3,8),'/','') as registerdate,
FROM TatEstelam.dbo.tblInquiryRealForeigners RL
LEFT JOIN TatEstelam.dbo.CustomerInfo CINFO
ON RL.IdentificationDocumentNumber ... | ```
SELECT * FROM
(
SELECT REPLACE(SUBSTRING(CreateDate,3,8),'/','') as registerdate,
FROM TatEstelam.dbo.tblInquiryRealForeigners RL LEFT JOIN TatEstelam.dbo.CustomerInfo CINFO
ON RL.IdentificationDocumentNumber = CINFO.NationalID
) AS registerdate
WHERE-- NationalID <> '0001'
IdentificationDocumentNumb... | using alias name in sql server 2012 | [
"",
"sql",
"sql-server-2012",
""
] |
I'm in the process of creating a temporary procedure in SQL because I have a value of a table which is written in markdown, so it appear as rendered HTML in the web browser *(markdown to HTML conversion)*.
String of the column currently look like this:
```
Questions about **general computing hardware and software** a... | Using the`STUFF`function and a simple`WHILE`loop:
```
CREATE FUNCTION dbo.fn_OddEvenReplace(@text nvarchar(500),
@textToReplace nvarchar(10),
@oddText nvarchar(10),
@evenText nvarchar(500))
RETURNS varc... | As per OP's request I have modified my earlier answer to perform as a temporary stored procedure. I have left my earlier answer as I believe the usage against a table of strings to be useful also.
If a Tally (or Numbers) table is known to already exist with at least 8000 values, then the marked section of the CTE can ... | How I can replace odd patterns inside a string? | [
"",
"sql",
"sql-server",
"sql-server-2014",
"dataexplorer",
""
] |
I have this little query that is working fine:
```
SELECT * FROM Components AS T1
WHERE Cost=null or Cost=''
Order by Code
```
Now I need to grab also the filed "description" from other tables where code=code
```
SELECT * FROM Components AS T1
WHERE Cost=null or Cost=''
LEFT JOIN on Table_321 AS T2
where T1.Code=T2... | ```
SELECT * FROM Components T1
LEFT JOIN Table_321 T2 ON T1.Code=T2.Code
LEFT JOIN Table3 T3 ON T3.Code = T1.Code
WHERE T1.Cost=null or T1.Cost=''
ORDER BY T1.Code
``` | ```
SELECT * FROM Components AS T1
LEFT JOIN Table_321 AS T2
ON T1.Code=T2.Code
WHERE Cost=null or Cost=''
Order by Code
``` | Query with JOIN on multiple tables | [
"",
"sql",
""
] |
I have a query that regularly returns "nothing", and I would like to run a different query if this is the case, but I know not of the way of doing this. If anyone could be of help please.
Here is the current code I am using...
`SELECT * FROM cfg_users JOIN cfg_ash ON cfg_users.iUserId = cfg_ash.iUserid WHERE iTeamId`... | A way you can do it is like this
* set two variables equal to the queries you want to execute.
* set another variable equal to the correct query when the first is not null.
* execute that query with a stored procedure.
**STORED PROCEDURE:**
```
DELIMITER $$
CREATE PROCEDURE `dynamic_query`(in input varchar(255))
BE... | There are some simple way only use sql.
Define your first query as a temp table, with union all, filter the second query with temp table's count.
```
with temp as (select * from t1 where 1=0)
select * from temp
union all
select * from t2 where (select count(*) from temp) =0
```
This query will return the second tab... | SQL IF SELECT query is null then do another query | [
"",
"mysql",
"sql",
"select",
"null",
""
] |
I am tasked with keeping several tables updated with information to be brought in from an external source. To this end, I've been hunting online for ways to pass table names as parameters, and all the answers are complex and/or throw errors (such as the below: "Incorrect syntax near 'Table' error shows)
```
CREATE PRO... | The short answer is that you can't parameterize the table name.
The longer answer is that can can accomplish what you want via *dynamic SQL*. It looks like you're using SQL Server. See the question *[Dynamic SQL - EXEC(@SQL) versus EXEC SP\_EXECUTESQL(@SQL)](https://stackoverflow.com/questions/548090/dynamic-sql-execs... | use dynamic SQL
```
DECLARE @sql as varchar(4000)
SET @sql = 'Delete from [S1].[MIRROR].[dbo].' + @tableName
+ ' Where [ID] in (Select [ID] from [S2].[DELTAS].[dbo].' + @tableName + ')'
EXEC(@sql)
```
As an example | Passing a Table name as a parameter | [
"",
"sql",
"sql-server",
"stored-procedures",
""
] |
Does `select * into B from A` also copy constraints of A on B ? If not, then how can I copy constraints? | No, not in SQL-Server. You would need to specify the constraints and indexes on the new table manually. If you're using SSMS, using the `Script As... Create To` functionality can get you a sample script to create a new table with the same constraints and structure.
<https://learn.microsoft.com/en-us/sql/t-sql/queries/... | You can not directly copy the constraint from one table to another table, first you should copy the table Structure with indexes and constraint, to do this
Please follow the instructions below:
1. In SSMS right click on the table, script create.
2. Change the name in the generated script to NewTable
insert into NewT... | Copying table constraints from select * into | [
"",
"sql",
"sql-server",
"select",
"constraints",
"select-into",
""
] |
Good Day
I am working of a existing SQL Server Database. What the developers did is to keep the Date and time separate. The Date is in DateTime format (what I want) but the time is incorrect. if it is 14:30 it shows as 1430 when its 09:25 shows as 925. I am trying tyo combine the date and time to have a Date Time view... | A different approach is to convert the time column in minutes and add it to the date
```
DATEADD(minute, T0.BeginTime / 100 * 60 + T0.BeginTime % 100
, CONVERT(VARCHAR, T0.BeginDate, 112))
```
with that the length of the time column doesn't matter | This should do the trick, Hope it helps.
```
DECLARE @DateTime TABLE (
DateWithTime DATE,
BeginTime INT);
INSERT INTO @DateTime
VALUES ('2014-08-04', '1525'),
('2014-08-04', '525'),
('2014-08-04', '15'),
('2014-08-04', '5'),
('2014-08-04', '0'),
('2014-08-04', '90')
;WITH cte_Beg... | CAST Correct VARCHAR to DateTime | [
"",
"sql",
"sql-server",
"date",
"datetime",
""
] |
I have below query
```
select Count(*), FUNCTIONAL_CLASS from RDF_NAV_LINK where
(LINK_ID NOT IN (Select DEST_LINK_ID from RDF_SIGN_DESTINATION) AND
LINK_ID NOT IN (Select ORIGINATING_LINK_ID from RDF_SIGN_ORIGIN))
GROUP BY FUNCTIONAL_CLASS
```
I like to show the Query output Like below
```
Count(*) FUNCTIONAL_CLAS... | With the WHERE clause, you have thrown away all information about the ignored rows.
To get the total count of rows, you have to count them separately:
```
SELECT count(*) || '/' || (SELECT count(*)
FROM RDF_NAV_LINK AS link2
WHERE link2.FUNCTIONAL_CLASS = link.FUN... | You could consider using LEFT JOINs to determine the LINK\_IDs that are missing in the ORIGIN and DESTINATION tables, as below:
```
SELECT
fn_class_groups.FUNCTIONAL_CLASS,
CONCAT(fn_class_groups.not_in_cnt,'/',fn_class_groups.total_cnt)
FROM
(SELECT
FUNCTIONAL_CLASS,
COUNT(rnl.LINK_ID) to... | Show Query output / Number of Total Records | [
"",
"sql",
"sqlite",
""
] |
I have a dataset that has a structure similar to this (greatly simplified for expository purposes):
```
CREATE TABLE FOO (
CUI CHAR(8),
SAB VARCHAR(40),
CODE VARCHAR(50),
KEY X_CUI (CUI)
);
```
There is no primary key: there are multiple rows with the same CUI value:
```
C0000039 MSH D015060
C000... | Try this:
```
select distinct cui
from foo where CUI not in (select distinct CUI from foo
where SAB = 'SNOMEDCT_US')
```
[SQL Demo](http://sqlfiddle.com/#!2/795ef/22) | Try this query :
```
SELECT DISTINCT CUI
FROM FOO
WHERE SAB != 'SNOMEDCT_US'
AND CUI NOT IN (SELECT DISTINCT CUI FROM FOO WHERE SAB = 'SNOMEDCT_US')
``` | A query to return a row only when that row lacks a particular value | [
"",
"mysql",
"sql",
""
] |
I am using an INSERT ... SELECT query in my MySQL. Now, in my database is a column named "medDate" which I use for my medicine Inventories app. This has a type Varchar and is formatted in this way, "July 2014". Now I want to use the insert...select query to copy the previous month's records. But as I test my query to M... | The functions `year()` and `month()` require dates. You can get the dates using `str_to_date()` because MySQL supports "partial" dates (i.e. those without days. So, try this:
```
WHERE YEAR(str_to_date(meddate, '%M %Y')) = YEAR(CURRENT_DATE - INTERVAL 1 MONTH) AND
MONTH(str_to_date(meddate, '%M %Y')) = MONTH(CUR... | As `medDate` is a string and not a DATETIME you can't use YEAR on this column, but you could convert the right side with DATE\_FORMAT and to be consistent you should store the values in the same format.
```
INSERT INTO medicinesinventory (itemName, compCode, classID,
medDate, price, beginningIn, newIn,
outMed, sal... | Using INSERT ... SELECT with Date format | [
"",
"mysql",
"sql",
"database",
""
] |
Today I need help with this really long select query.
The thing is I need to get all records from 1 table "dispositivos" and then LEFT JOIN "monitoreo", some other tables, and the most important part of this query is joining the table "incidencia".
One "dispositivo" can have many "incidencia", and from all the "incid... | ```
'SELECT d.id, d.tipo_dispositivo_id, d.unidad_adscripcion_id, d.nro_cns, d.cod_inter, d.nombre_senal, d.lat as lat_origen, d.long as long_origen, '+
'd.direccion_latitud_id, d.direccion_longitud_id, d.descripcion, d.alc, d.ele, d.cod_iala_id, d.sistema_acceso_id, d.color_bombillo_id, '... | One approach to solving this problem is to use an inline view that returns the unique identifier of the rows from "incidencia" you want to return, and then join that to the inidencia table to get the rows.
e.g.
```
LEFT
JOIN ( SELECT l.fecha_incidente
, MIN(l.alerta_id) AS lowest_alerta_id
FROM inc... | MySQL Query with LEFT JOIN (SELECT) ORDER and LIMIT | [
"",
"mysql",
"sql",
"join",
"sql-order-by",
"limit",
""
] |
So I have two tables, the first would be users\_
```
Name
------
Carol
Sue
```
and the second would be interests\_
```
Name Interest
----------------------
Carol Books
Carol Dancing
Carol Sports
Sue Books
Sue Dancing
```
The user will be presented with checkboxes to sele... | Here is the simple way to do it
```
select
i.name
from interests i
where i.interest in ('Books','Dancing')
and not exists
(
select 1 from interests i1
where interest not in ('Books','Dancing')
AND i.name = i1.name
)
group by i.name
having count(*) = 2
```
**[DEMO](http://www.sqlfiddle.com/#!9/08e54/1)** | so basically to do this build a negative list of users that have more than those two and then select the others
```
SELECT u.name
FROM users_ u
JOIN interests_ i ON i.name = u.name
JOIN
( SELECT u.name
FROM users_ u
JOIN interests_ i ON i.name = u.name
WHERE i.interest NOT IN('Books', 'Dancing')
)... | SQL select one row from table 1 joining on multiple rows in table 2 | [
"",
"mysql",
"join",
"sql",
""
] |
I'm trying to write a nested joins query with a condition.
The query I have right now is:
```
Event.joins(:store => :retailer).where(store: {retailer: {id: 2}})
```
Which outputs the following SQL:
```
SELECT "events".* FROM "events" INNER JOIN "stores" ON "stores"."id" = "events"."store_id" INNER JOIN "retailer... | Looks like you don't need nested joins here. Try to use something like
```
Event.joins(:store).where(stores: {retailer_id: 2})
```
Nested join should also work using `stores`
```
Event.joins(:store => :retailer).where(stores: {retailer: {id: 2}})
``` | There is the simplest way instead of using curly brackets :
```
Event.joins(:store => :retailer).where('stores.retailer_id => ?', 2)
``` | Rails Nested Joins Activerecord with conditions | [
"",
"sql",
"ruby-on-rails",
"rails-activerecord",
""
] |
In a database that have Orders, Customers tables, i need the relation between these two tables to be zero or one to many relationship, simply because in my application, an order can exist without being assigned to a customer.
One first idea that comes to my mind is to make the foreign key nullable, this way when creat... | Create your 1:n relationship as normal. Then double click the table to bring up the details. On your new FK field, uncheck the "NN" column. Now your FK can be NULL. | Mandatory option in "Foreign Key" tab in "Relationship" tab appears to be the way to control optionality. | How to create a zero or one to many relationship in Mysql workbench | [
"",
"mysql",
"sql",
"mysql-workbench",
""
] |
Hi there guys basically I have this query and I sort of get half of it but not all of it can someone please help me work it out?
[Query](http://gyazo.com/8e372fe56c9f9c5c28f77739bfa10e9c)
Thanks in advance! :)! | ```
SELECT username,first_name, last_name from members ORDER BY join_date DESC LIMIT 5;
``` | > List the username, first name, last name and date of joining of the five most recent members to register an account. List the results with the most recent registration first.
```
SELECT `username`,`firstname`,`lastname`,`join_date`
FROM `members`
ORDER BY `join_date` DESC
LIMIT 5
```
> @hd Oops sorry but here is th... | How do I fix this MYSQL query | [
"",
"mysql",
"sql",
""
] |
I have two tables in SQL Server: Household and People. Household represents a home and People represents the people living in the home:
**Household**
```
Id Address City State Zip
------------------------------------------------------
1 123 Main Anytown CA 90121... | This is done using a dynamic cross tab. For reference: <http://www.sqlservercentral.com/articles/Crosstab/65048/>
```
CREATE TABLE HouseHold(
ID INT,
Address VARCHAR(20),
City VARCHAR(20),
State CHAR(2),
Zip VARCHAR(10)
)
CREATE TABLE People(
ID INT,
HouseHoldID INT,
... | This is adapted from a script I use with a similar requirement. Probably don't want to use if the People table has a million rows, but works well enough for my use case with about 20000 rows:
```
DECLARE @id int, @householdid int, @name varchar(50), @age int, @currentid int, @peoplecount int;
DECLARE @colsql nvarcha... | Flatten parent child relationship in SQL Server | [
"",
"sql",
"sql-server",
""
] |
I have a bit parameter
```
@IsInRetry
```
If it is false I have to set the where condition to
```
attempts = 0
```
else if it is true I have to set the where condition to
```
attempts > 0
```
How could this be done? | Try this way:
```
( (@IsInRetry = 0 and attempts = 0) or (@IsInRetry = 1 and attempts > 0) )
``` | Try this:
```
WHERE (attempts = @IsInRetry or (@IsInRetry = 1 and attempts > 0))
``` | SQL Server : IF Condition in WHERE clause | [
"",
"sql",
"sql-server",
""
] |
I have this one table `empname`, `age`, and `gender`
```
empname age gender
Nana 24 F
Jillian 28 M
Sally 29 F
David 30 M
Mike 35 M
Daisy 37 F
```
and the question is how do i count the gender who is female<30 years old... | The easiest way would be using multiple sub-queries:
```
SELECT
(SELECT COUNT(*) FROM employee WHERE gender = F AND age<30) AS 'Female Below 30',
(SELECT COUNT(*) FROM employee WHERE gender = F AND age>=30) AS 'Female Above 30',
(SELECT COUNT(*) FROM employee WHERE gender = M AND age<30) AS 'Male Below 30',
(SELECT CO... | You can query like this:
```
select
count(case when gender='F' and age >= 30 then 1 end) "Female>=30",
count(case when gender='F' and age < 30 then 1 end) "Female<30",
count(case when gender='M' and age >= 30 then 1 end) "Male>=30",
count(case when gender='M' and age < 30 then 1 end) "Male>30"
from ...
```
Yo... | How to count multiple things in 1 column | [
"",
"sql",
""
] |
I have a table with alot of missing identity ids missing. I would also like to start it back at 1 with.
```
DBCC CHECKIDENT('Customer', RESEED, 0)
```
However, there is existing data in the table, so will this effect anything?
Say I have ID 2,3,5 in the table with 1 and 4 gone. If I execute the SQL above, does that ... | RESEEDING to 0 on table with existing data will cause duplicates of existing ID or raise error when Unique Constraints is available. Please see POC for further clarification of the same
**TestData:**
```
IF OBJECT_ID(N'Table1') > 0
BEGIN
DROP TABLE Table1
END
CREATE TABLE Table1 (ID INT IDENTITY(1, 1),... | Although missing ids are not aesthetically pleasing to the eye, they make absolutely no difference to the database performance.
If you are using these values to display something like a Customer Ref to the user, then you should use a separate field for this. Database IDs should not be relied upon for display, as the r... | Reseed back 1 with existing data in SQL Server | [
"",
"sql",
"sql-server",
"identity-column",
""
] |
i have this query for insert list of data in table
and now i want avoid insert duplicate records
how i can do it in my code?
please help me
```
-- Create a table type to match your input parameters
CREATE TYPE IdNameTable AS TABLE
( ID INT, Name NVARCHAR(50) );
GO
-- change your stored procedure to accept such a ta... | Try this way:
```
INSERT INTO dbo.Group (Id, Name)
SELECT
Id, Name
FROM
@Values
WHERE
ID NOT IN (select ID from Group)
```
with full code:
```
-- Create a table type to match your input parameters
CREATE TYPE IdNameTable AS TABLE
( ID INT, Name NVARCHAR(50) );
GO
-- change your stored procedure to accept ... | I have used a NOT EXISTS to check to see if ID is available in dbo.Group table and insert only when no match is found. The assumption is that ID is Unique. Please modify the filter inside the Not EXISTS to tiler for your need. Hope it helps
```
CREATE TYPE IdNameTable AS TABLE
(ID INT, NAME NVARCHAR(50));
GO
-- chan... | how to avoid inserting duplicate records in table type sql server | [
"",
"sql",
"sql-server",
""
] |
Given a really simple table in MS SQL like this:
```
User ID | Status
----------------
1 False
2 True
2 False
3 False
3 False
```
I'm having trouble wrapping my head around how I would select only users that *don't* have any rows with a `Status` assigned to `True`.
The result ... | You can use a `GROUP BY` with a `HAVING` clause to get the result. In your `HAVING` you can use a `CASE` expression with an aggregate to filter out any rows that have a `Status = 'True'`:
```
select [user id]
from table1
group by [user id]
having sum(case when status = 'true' then 1 else 0 end) < 1;
```
See [SQL Fidd... | Try this way:
```
select distinct userid
from yourtable
where userid not in (select userid
from yourtable
where status = 'True')
``` | Selecting rows in SQL only where *all* values do not meet a certain criteria | [
"",
"sql",
"t-sql",
"group-by",
""
] |
Here's my Query to find id's for userid 2, I want to run a query that finds entries where userid=2 and amount>1 AND userid 1 has none of that id
```
SELECT id, amount FROM collection WHERE userid='2' AND amount>1
```
I'm not sure how to do an if statement inside a SQL query, but there has to be a way to easily do thi... | If I understand right, you want The list of users having user ID = 2 and amount > 1. This list should ignore the records where ID is not in user ID = 1
**Sample Input/Ouput:**
```
ID UserID Amount Returned?
1 2 0 No (Amount 0)
2 2 10 Yes
3 1 10
3 2 5 (No, since ID =3 exists ... | *"where userid=2 and amount>1 AND userid 1 has none of that id"*
You can use `NOT EXISTS`:
```
SELECT id, amount
FROM collection c
WHERE c.userid = '2'
AND c.amount > 1
AND NOT EXISTS
(
SELECT 1 FROM collection c2
WHERE c2.userid = '1'
AND c.id = c2.id
)
``` | SQL Select where user1 has more than one and user2 has none | [
"",
"mysql",
"sql",
""
] |
I have a Database Table where i have some data in XML datatype.
Following is an example of some data in that column.
```
<locale en-US="Test & Data" />
```
Is there any way to extract only the words "Test & Data" in SQL server. Is there any built in function. | Try something like this.
If you have a XML variable:
```
declare @xml XML = '<locale en-US="Test & Data" />';
select
data.node.value('@en-US', 'varchar(11)') my_column
from @xml.nodes('locale') data(node);
```
In your case, for a table's column (sorry for not given this example first):
```
create table dbo.... | ```
IF OBJECT_ID('tempdb..#Holder') IS NOT NULL
begin
drop table #Holder
end
CREATE TABLE #Holder
(ID INT , MyXml xml )
/* simulate your insert */
INSERT INTO #HOLDER (ID , MyXml)
select 1 , '<locale en-US="Test & Data" />'
union all select 2 , '<locale en-US="Barney & Friends" />'
/* with other valu... | Converting XML in SQL Server | [
"",
"sql",
"sql-server",
"xml",
""
] |
I encountered a strange behavior of the `binary_double` rounding with Oracle SQL. `binary_double` values should be rounded `half even` according to the [documentation](http://docs.oracle.com/cd/B19306_01/server.102/b14200/functions135.htm), but when testing this with the following queries, it seems that there are some ... | Let's have a look at the first example, since others are pretty much the similar:
The `0.0000075` in double precision IEEE 754 is presented as `7.50000000000000019000643072808E-6`
The `0.0000065` is presented as `6.49999999999999959998360846147E-6`
When you round both by 6 - the former becomes `8e-6`, the latter `6e... | You should better use the DECIMAL data type to avoid rounding issues.
More info here : <http://docs.oracle.com/javadb/10.6.2.1/ref/rrefsqlj15260.html>
Try this one:
```
select 1,round(cast (0.0000075 as decimal(15,7)),6), round(cast (0.0000065 as decimal(15,7)),6) from dual;
```
Since I have no Oracle database inst... | Oracle SQL rounding misbehavior | [
"",
"sql",
"oracle",
"casting",
"rounding",
""
] |
I have two tables `Tbl_A` and `Tbl_B` and data is as follows
Tbl\_A
```
Company_nm Website
Airindia www.airindia.coin/index.html
Spicejet www.spicjet.com
indigo indigo.com/
```
Tbl\_B
```
Company URL
Airindia www.airindia.co.in/index
Spicejet www.spicjet.com/index.html
indigo www.in... | You can use `substring` and `charindex` to get the first part of the url:
```
select *
from tbl_a a
join tbl_b b
on case
when charindex('/', a.website) > 0
then substring(a.website, 0, charindex('/', a.website))
else a.website
end
=
case
when charindex('/', b.ur... | i think you must use a 'pattern matching' way for your select query.
have a look at [Regular Expressions](http://msdn.microsoft.com/en-us/magazine/cc163473.aspx)
and [Pattern Matching (Regex)](http://www.sqllion.com/2010/12/pattern-matching-regex-in-t-sql/)
for more Information. | Replace in Joins | [
"",
"sql",
"sql-server-2008",
""
] |
Given a `Dictionary` table {`word_id`, `word`}.
`word` is char(32), `word_id` is int, IDENTITY and PRIMARY KEY.
I need to ensure some words exist in the `Dictionary` table. If they don't exist, those need to be added. I am having a hard time trying to wrap NOT EXISTS clause around several constant value.
Suppose the... | Another way is using a [CTE](http://msdn.microsoft.com/en-us/library/ms175972.aspx), either by providing the column name in the expression:
```
WITH Data(Word) AS
(
SELECT 'test1'
UNION ALL
SELECT 'test2'
UNION ALL
SELECT 'hello'
)
SELECT Word FROM Data
WHERE NOT EXISTS( SELECT 1 FROM Dictionary d
... | You can warp the `UNION ALL` in another `SELECT`, give an alias to the word column, and put parentheses around the nested query, so that the `WHERE` clause applies to all rows of the union:
```
SELECT * FROM (
SELECT 'test1' AS word
UNION ALL
SELECT 'test2' AS word
UNION ALL
SELECT 'hello' AS word
) ww
WHE... | NOT EXISTS with several constant rows | [
"",
"sql",
"sql-server",
"constants",
"not-exists",
""
] |
I need to extract some data to analyse exceptions/logs, and I'm stuck at a point.
I have a table with a column called `CallType`, and a status which can be **Success** or **Failure**. This table also has a column called `SessionId`.
I need to do this:
Select all the `SessionId`'s where all the `CallType = 'A'` are m... | I would do this with conditional aggregation in the `having` clause:
```
select top 10 *
from Log nolock
where ProviderId=48 -- add more conditions here
group by SessionId
having sum(case when CallType = 'A' and Status = 'Failure' then 1 else 0 end) = 0 and
sum(case when CallType = 'B' and Status = 'Failure' t... | Having clause can only operate on aggregates within the group so this isn't the correct way to go about it since you are filtering out other rows you want to check against. I'd use `EXISTS` for this e.g.
**edit**: corrected the query
```
SELECT *
FROM Log L WITH(NOLOCK)
WHERE ProviderId = 48
AND CallType = 'A'
AND St... | How can I write this select query in SQL Server? | [
"",
"sql",
"sql-server",
""
] |
I have created one temporary table named "table1". I am trying to list the columns of my temp table. I am not getting any values. Here is my mysql query.
```
SELECT column_name
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_name = 'table2';
```
Any body help me please?
Thanks | You cannot get the temporary table columns using the [INFORMATION\_SCHEMA](http://dev.mysql.com/doc/refman/5.5/en/tables-table.html)
The only way which you can use is to go with `SHOW CREATE TABLE table2`
"INFORMATION\_SCHEMA.COLUMNS" does not contains columns of temporary table. | You can use SHOW COLUMS to achieve this.
Example Table:
```
CREATE TEMPORARY TABLE SalesSummary (
product_name VARCHAR(50) NOT NULL,
total_sales DECIMAL(12,2) NOT NULL DEFAULT 0.00,
avg_unit_price DECIMAL(7,2) NOT NULL DEFAULT 0.00,
total_units_sold INT UNSIGNED NOT NULL DEFAULT 0
);
```
Command:
SHOW COLUMNS FROM... | List temporary table columns in mysql | [
"",
"mysql",
"sql",
""
] |
```
SELECT e.cempnoee, e.cempname, e.cempemail, s.csrvposition, s.csrvbranch, s.csrvcostcentr, b.cbrndesc, p.caddnophoneh FROM emas e
inner join esrvc s on e.cempnoee = s.csrvnoee
inner join cbranch b on s.csrvbranch = b.cbrncode
inner join eaddrs p on e.cempnoee = p.caddnoee
```
The SQL dial... | After corresponding with the author of Lianja, spliting the SQL statement works:
```
SELECT emas.cempnoee, emas.cempname, emas.cempemail, esrvc.csrvposition, esrvc.csrvbranch, esrvc.csrvcostcentr FROM emas inner join esrvc on emas.cempnoee = esrvc.csrvnoee into cursor esc
SELECT *, cbranch.cbrndesc FROM esc inner join... | Actually Lianja does support multiple joins, it's just a bit weird syntax
Try something like this, and it should work
```
SELECT emas.cempnoee, emas.cempname,;
emas.cempemail, esrvc.csrvposition,;
esrvc.csrvbranch, esrvc.csrvcostcentr,;
cbranch.cbrndesc, eaddrs.caddnophoneh;
FROM emas INNER JOIN ... | How do I split two or more inner joins into multiple select statements | [
"",
"sql",
""
] |
So I'm working on a system that uses default date values of '1900-01-01 00:00:00.000' rather than allowing nulls. I've got a stored procedure that displays all members of an association and the date and amounts charged to them. If a member has not received charges, I need to display a zero amount and empty string for t... | The problem is that all possible values of a CASE statement must have the same DataType, and the most restrictive possibility will be used.
You are trying to return an empty string in one case, but in the other case you return a DateTime type. That means that the empty string will be implicitly converted to a DateTime... | Change this:
```
WHEN cs.trandate = '1900-01-01 00:00:00.000' THEN ''
```
into this
```
WHEN CAST(cs.trandate AS DATE) = '19000101' THEN NULL
```
Comparing date-times is always fraught with error for the same reason comparing floats is. This just pulls the actual date part and does the comparison, which is good eno... | Stored procedure to suppress default values of '1900-01-01 00:00:00.000' | [
"",
"sql",
"sql-server",
"case",
""
] |
I have a list of names.
john, sam, peter, jack
I want to query the same sql with each of above as the filter. Each query will give me a unique employee id, which I want to use to delete some other records.
```
select emp_id from employee where emp_name like '%john%';
```
Let's say for the first query, I get the id ... | Perhaps the following will help:
```
BEGIN
FOR aName IN (SELECT 'john' AS EMP_NAME FROM DUAL
UNION ALL
SELECT 'sam' AS EMP_NAME FROM DUAL
UNION ALL
SELECT 'peter' AS EMP_NAME FROM DUAL
UNION ALL
SELECT 'jack' AS EMP_N... | Do you really need a cursor to do so? Try to skip cursor if possible to avoid poor performance/memory usage on huge data.
```
delete from account_details inner join employee on account_details.emp_id = employee.emp_id where WHERE CONTAINS(employee.emp_name, '"John" OR "Sam" OR "Max"', 1) >0;
delete from hr_details in... | PL SQL loop through list of ids | [
"",
"sql",
"oracle",
"plsql",
"oracle-sqldeveloper",
"plsqldeveloper",
""
] |
I have a table with 3 rows, where i did fill all the collumns with atributes. I can't understand why when i do this:
```
SELECT count(*) FROM person WHERE NULL is NULL;
```
it gives me the result: 3.
can you please explain me? | In SQL, `NULL = NULL` is not true. However, `NULL IS NULL` is indeed true, and equivalent to `1=1`. Therefore, you get all the rows.
For example, as per MSDN documentation for SQL Server:
> If the value of expression is NULL, IS NULL returns TRUE; otherwise, it returns FALSE.
>
> If the value of expression is NULL, I... | Because for every row condition
```
NULL is NULL
```
is always true, so there is no reason to filter the rows.
Below condition could be the opposite of above condition
```
1=0
```
with this condition you will get 0 rows because for every row the condition is false. | Understand the is null query in sql | [
"",
"sql",
"null",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.